<script setup lang="ts"  generic="T">
import type { ComponentExposed } from 'vue-component-type-helpers'
import type DataForm from './DataForm.vue'
import type { DataFormDrawerProp } from '@/components/DataForm/types'

import { ref } from 'vue'

const { fields, title } = defineProps <DataFormDrawerProp<T>>()

const emits = defineEmits<{
  success: [title?: string, data?: any]
}>()

const formData = defineModel<any>('formData', { required: true })
const formVisible = defineModel<boolean>('formVisible', { required: true })
const formRef = ref<ComponentExposed<typeof DataForm>>()

function close() {
  formVisible.value = false
}

async function onFormSuccess(data: any) {
  ElMessage.success(`${title}成功`)
  await emits('success', title, data)
  formVisible.value = false
}
</script>

<template>
  <el-drawer
    v-if="formData"
    v-model="formVisible"
    :title="title"
    destroy-on-close
    append-to-body
    center
    resizable
    :size="width ?? (cols === undefined ? '30%' : `${(cols as number - 1) * 10 + 30}%`)"
    @closed="formData = undefined"
  >
    <slot name="test" />
    <data-form
      ref="formRef"
      v-model="formData"
      :fields="fields"
      :disabled="disabled"
      :cols="cols"
      :size="size"
      :submit="submit"
      @success="onFormSuccess"
    >
      <template
        v-for="field in fields"
        :key="field.name"
        #[field.name]="slotProps"
      >
        <slot :name="field.name" v-bind="slotProps" />
      </template>
    </data-form>

    <template v-if="!disabled && submit && formRef" #footer>
      <el-button size="default" @click="close">
        取消
      </el-button>
      <el-button size="default" type="primary" :loading="formRef.formLoading" @click="formRef.submitForm">
        保存
      </el-button>
    </template>
  </el-drawer>
</template>
